﻿using AutoMapper;
using B.S.Filtration.Domain;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Write.Api.Application.Command.Tickets;
using MediatR;
using SqlSugar;

namespace B.S.Filtration.Write.Api.Application.CommandHander.Tickets
{
    public class DeleteTicketHander : IRequestHandler<DeleteTicketCommand, APIResult<int>>
    {

        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public DeleteTicketHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 删除工单信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<int>> Handle(DeleteTicketCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var list = await db.Queryable<Domain.Tickets>().FirstAsync(x => x.TicketId == request.TicketId);

            // 增加判空逻辑
            if (list == null)
            {
                result.code = APIResultCode.failed;
                result.msg = "未找到要删除的过程监控";
                return result;
            }

            var one = await db.Deleteable<Domain.Tickets>(list).ExecuteCommandAsync();
            if (one > 0)
            {
                result.code = APIResultCode.success;
                result.msg = " 过程监控删除成功";
            }
            else
            {
                result.code = APIResultCode.failed;
                result.msg = "过程监控删除失败";
            }
            return result;
        }
    }
}
